package com.water.expert.extraction.security;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity // 在方法上启用 @PreAuthorize
public class SecurityConfig {
	@Bean
	public SecurityFilterChain defaultServerSecurityFilterChain(HttpSecurity http) throws Exception {
		
		http.authorizeHttpRequests(
				auth -> auth.requestMatchers("/login").permitAll().anyRequest().authenticated());
		// http.csrf(csrf -> csrf.disable()); // 可禁用 CSRF（视情况而定）
		// OAuth2 登录:只要pplication.yml配置了OAuth2提供商，无需额外配置loginPage()
		// 启用oauth2Login()后，访问未授权页面时，默认行为是跳转到OAuth2认证端点 (/oauth2/authorize) 而不是自定义登录页面
		// http.oauth2Login(Customizer.withDefaults());
		// http.oauth2Login(oauth2 -> oauth2.loginPage("/custom")); // ✅ 自定义登录页面

		// 允许作为OAuth2客户端访问受保护资源
		// http.oauth2Client(Customizer.withDefaults());
		// http.oauth2Login(config->config.loginPage("/login").permitAll());
//		http.logout(logout -> logout
//	        .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
//	        .logoutSuccessHandler(new CustomLogoutSuccessHandler())
//	        .invalidateHttpSession(true)
//	        .clearAuthentication(true)
//	    );
		http.logout(logout -> logout.logoutSuccessUrl("http://authserver:9999/logout"));
		http.oauth2Login(Customizer.withDefaults());
		http.oauth2Client(Customizer.withDefaults());
		// JWT资源服务器,处理OAuth2 令牌
		http.oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter())));
		return http.build();
	}

	@Bean
	public JwtAuthenticationConverter jwtAuthenticationConverter() {
		JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
		jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwt -> {
			List<String> scopes = jwt.getClaimAsStringList("scope"); // 解析 scope 字段
			return scopes.stream().map(scope -> new SimpleGrantedAuthority("SCOPE_" + scope)) // 生成 Spring Security 权限
					.collect(Collectors.toList());
		});
		return jwtAuthenticationConverter;
	}

}